import { defineConfig } from "vite";
import path from "path";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import viteVConsole from "vite-plugin-vconsole";
import { mockDevServerPlugin } from "vite-plugin-mock-dev-server";
import { visualizer } from "rollup-plugin-visualizer";
import compression from "vite-plugin-compression";

export default defineConfig(({ command }) => ({
  // base: "/xiaomi-web/",
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
      imports: ["vue", "vue-router", "pinia"],
      dts: "src/auto-imports.d.ts",
    }),
    Components({
      resolvers: [ElementPlusResolver()],
      dts: "src/components.d.ts",
    }),
    viteVConsole({
      entry: [path.resolve("src/main.ts")],
      enabled: command !== "build",
      config: {
        maxLogNumber: 1000,
        theme: "dark",
      },
    }),
    compression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: "gzip",
      ext: ".gz",
    }),
    visualizer({
      open: true,
      gzipSize: true,
      brotliSize: true,
    }),
  ],
  resolve: {
    extensions: [".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
  css: {
    devSourcemap: true,
    lightningcss: {
      drafts: {
        values: {
          customProperties: true,
        },
      },
    },
  },
  build: {
    outDir: "xiaomi-web",
    assetsDir: "assets",
    sourcemap: command !== "build",
    minify: "terser",
    terserOptions: {
      compress: {
        drop_console: command === "build",
        drop_debugger: command === "build",
        pure_funcs: command === "build" ? ["console.log"] : [],
      },
    },
    emptyOutDir: true,
    manifest: true,
    chunkSizeWarningLimit: 1500,
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes("node_modules")) {
            return id
              .toString()
              .split("node_modules/")[1]
              .split("/")[0]
              .toString();
          }
        },
        chunkFileNames: "assets/js/[name]-[hash].js",
        entryFileNames: "assets/js/[name]-[hash].js",
        assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
      },
    },
  },
  server: {
    cors: true, // 允许跨域
    port: 8000,
    open: true,
    host: "0.0.0.0",
    proxy: {
      api: {
        target: "http://localhost:3000",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
    hmr: {
      overlay: true,
    },
  },
  optimizeDeps: {
    include: ["vue", "vue-router", "pinia", "axios"],
    exclude: ["@vueuse/core"],
  },
  esbuild: {
    target: "es2020",
  },
}));
